package tech.runchen.gz5055.oms.modules.system.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import tech.runchen.gz5055.oms.common.annotation.RequiresPermissions;
import tech.runchen.gz5055.oms.common.annotation.SysLog;
import tech.runchen.gz5055.oms.common.base.AbstractController;
import tech.runchen.gz5055.oms.common.enums.BusinessType;
import tech.runchen.gz5055.oms.common.enums.ReturnOrderStatus;
import tech.runchen.gz5055.oms.common.enums.UserType;
import tech.runchen.gz5055.oms.common.utils.PageInfo;
import tech.runchen.gz5055.oms.common.utils.Result;
import tech.runchen.gz5055.oms.common.utils.redis.delay.RedisDelayQueueManager;
import tech.runchen.gz5055.oms.common.utils.redis.delay.ReturnTimeoutCheckTask;
import tech.runchen.gz5055.oms.modules.system.entity.OrderDetailEntity;
import tech.runchen.gz5055.oms.modules.system.entity.OrderEntity;
import tech.runchen.gz5055.oms.modules.system.entity.ReturnOrderDetailEntity;
import tech.runchen.gz5055.oms.modules.system.entity.ReturnOrderEntity;
import tech.runchen.gz5055.oms.modules.system.form.ReturnOrderCheckForm;
import tech.runchen.gz5055.oms.modules.system.form.ReturnOrderShipmentForm;
import tech.runchen.gz5055.oms.modules.system.service.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 退货单信息表 前端控制器
 * </p>
 *
 * @author zzj
 * @since 2023-12-20
 */
@Api(tags = "管理平台 - 退货单管理")
@RestController
@RequestMapping("/sys/order/return")
public class SysReturnOrderController extends AbstractController {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private IReturnOrderService returnOrderService;
    @Autowired
    private IReturnOrderDetailService returnOrderDetailService;
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private RedisDelayQueueManager redisDelayQueueManager;

    @ApiOperation("退货单列表")
    @RequiresPermissions(value = {UserType.SPD, UserType.NURSE})
    @GetMapping("/list")
    public Result list(@RequestParam Map<String, Object> params) {
        params.put("userType", getLoginUser().getUser().getType());
        params.put("userId", getUserId());
        PageInfo page = returnOrderService.queryPage(params);
        return Result.success(page);
    }

    @ApiOperation("退货单详情")
    @RequiresPermissions(value = {UserType.SPD, UserType.NURSE})
    @GetMapping("/{returnOrderId}")
    public Result info(@PathVariable("returnOrderId") Long returnOrderId) {
        ReturnOrderEntity returnOrder = returnOrderService.getById(returnOrderId);
        if (returnOrder != null) {
            returnOrder.setReturnOrderDetailList(returnOrderDetailService.queryReturnOrderDetailList(returnOrderId));
        }
        return Result.success(returnOrder);
    }

    @ApiOperation("根据订单ID查询退货单详情")
    @RequiresPermissions(value = {UserType.SPD, UserType.NURSE})
    @GetMapping("/by/{orderId}")
    public Result infoByOrderId(@PathVariable("orderId") Long orderId) {
        ReturnOrderEntity returnOrder = returnOrderService.queryInfoByOrderId(orderId);
        if (returnOrder != null) {
            returnOrder.setReturnOrderDetailList(returnOrderDetailService.queryReturnOrderDetailList(returnOrder.getId()));
        }
        return Result.success(returnOrder);
    }

    @SysLog(title = "创建退货单", businessType = BusinessType.INSERT)
    @ApiOperation("创建退货单")
    @RequiresPermissions(value = {UserType.SPD, UserType.NURSE})
    @PostMapping("/create")
    public Result create(@Validated @RequestBody ReturnOrderEntity returnOrder) {
        OrderEntity order = orderService.getById(returnOrder.getOrderId());
        if (order == null) {
            return Result.error("订单信息不存在");
        }
        returnOrder.setInitiateTime(System.currentTimeMillis());
        returnOrder.setInitiateUserId(getUserId());
        returnOrder.setInitiateUserName(getNickName());
        returnOrder.setPickupAddress(order.getDeliveryAddress());
        returnOrder.setPickupAddressId(order.getDeliveryAddressId());
        if (getLoginUser().getUser().getType().equals(UserType.SPD.getCode())) {
            returnOrder.setStatus(ReturnOrderStatus.CONFIRM.getValue());
            returnOrder.setConfirmOrderTime(System.currentTimeMillis());
            returnOrder.setConfirmOrderUserId(getUserId());
            returnOrder.setConfirmOrderUserName(getNickName());
        } else {
            returnOrder.setStatus(ReturnOrderStatus.WAIT.getValue());
        }
        returnOrderService.saveReturnOrder(returnOrder);
        //更新退货次数
        order.setReturnNumber(1);
        orderService.updateOrder(order);
        // 创建即时消息
        noticeService.createReturnOrderNotice(returnOrder, ReturnOrderStatus.WAIT);
        // 设置退货单确认超时提醒
        redisDelayQueueManager.addTask(new ReturnTimeoutCheckTask(ReturnTimeoutCheckTask.TAG + returnOrder.getId(), returnOrder.getId().toString(), ReturnTimeoutCheckTask.TIMEOUT));
        return Result.success();
    }

    @SysLog(title = "确认退货单", businessType = BusinessType.OPERATE)
    @ApiOperation("确认退货单")
    @RequiresPermissions(value = {UserType.SPD})
    @PutMapping("/confirm/{returnOrderId}")
    public Result confirm(@PathVariable("returnOrderId") long returnOrderId) {
        ReturnOrderEntity returnOrder = returnOrderService.getById(returnOrderId);
        if (returnOrder.getStatus() != ReturnOrderStatus.WAIT.getValue()) {
            return Result.error("订单状态异常，请刷新后重试");
        }
        //订单确认状态及确认人
        returnOrder.setStatus(ReturnOrderStatus.CONFIRM.getValue());
        returnOrder.setConfirmOrderTime(System.currentTimeMillis());
        returnOrder.setConfirmOrderUserId(getUserId());
        returnOrder.setConfirmOrderUserName(getNickName());
        returnOrderService.updateReturnOrder(returnOrder);
        return Result.success();
    }

    @SysLog(title = "装车确认", businessType = BusinessType.OPERATE)
    @ApiOperation("装车确认")
    @RequiresPermissions(value = {UserType.NURSE})
    @PutMapping("/loadConfirm")
    public Result loadConfirm(ReturnOrderShipmentForm returnOrderShipment) {
        ReturnOrderEntity returnOrder = returnOrderService.getById(returnOrderShipment.getReturnOrderId());
        if (returnOrder.getStatus() != ReturnOrderStatus.CONFIRM.getValue()) {
            return Result.error("订单状态异常，请刷新后重试");
        }
        returnOrder.setStatus(ReturnOrderStatus.SHIPPED.getValue());
        returnOrder.setConfirmLoadTime(System.currentTimeMillis());
        returnOrder.setConfirmLoadUserId(getUserId());
        returnOrder.setConfirmLoadUserName(getNickName());
        returnOrderService.updateReturnOrder(returnOrder);
        // 创建即时消息
        noticeService.createReturnOrderNotice(returnOrder, ReturnOrderStatus.SHIPPED);
        // 移除发货超时提醒
        redisDelayQueueManager.removeTask(ReturnTimeoutCheckTask.TAG + returnOrder.getId());
        // 设置配送超时提醒
        redisDelayQueueManager.addTask(new ReturnTimeoutCheckTask(ReturnTimeoutCheckTask.TAG + returnOrder.getId(), returnOrder.getId().toString(), ReturnTimeoutCheckTask.TIMEOUT));
        return Result.success(returnOrder);
    }

    @SysLog(title = "核验退货单", businessType = BusinessType.OPERATE)
    @ApiOperation("核验退货单")
    @RequiresPermissions(value = {UserType.SPD})
    @PutMapping("/check")
    public Result check(@Validated @RequestBody ReturnOrderCheckForm returnOrderCheck) {
        ReturnOrderEntity returnOrder = returnOrderService.getById(returnOrderCheck.getReturnOrderId());
        if (returnOrder == null || returnOrder.getStatus() == ReturnOrderStatus.CANCEL.getValue()) {
            return Result.error("退货单不存在或已经取消");
        }
        List<OrderDetailEntity> list = orderDetailService.queryOrderDetailList(returnOrder.getOrderId());
        for (OrderDetailEntity orderDetail : list) {
            ReturnOrderDetailEntity returnOrderDetail = returnOrderCheck.getReturnOrderDetailList().stream().filter((p) -> p.getProductId().equals(orderDetail.getProductId())).findAny().orElse(null);
            orderDetail.setOriginalQuantity(orderDetail.getQuantity());
            if (returnOrderDetail != null) {
                orderDetail.setQuantity(returnOrderDetail.getCheckQuantity());
            }
            orderDetailService.updateById(orderDetail);
        }
        returnOrder.setStatus(ReturnOrderStatus.CHECKED.getValue());
        returnOrderService.updateReturnOrder(returnOrder);
        // 创建即时消息
        noticeService.createReturnOrderNotice(returnOrder, ReturnOrderStatus.CHECKED);
        // 移除配送超时提醒
        redisDelayQueueManager.removeTask(ReturnTimeoutCheckTask.TAG + returnOrder.getId());
        return Result.success();
    }

    @SysLog(title = "取消退货单", businessType = BusinessType.OPERATE)
    @ApiOperation("取消退货单")
    @RequiresPermissions(value = {UserType.SPD, UserType.NURSE})
    @PutMapping("/cancel/{returnOrderId}")
    public Result cancel(@PathVariable("returnOrderId") long returnOrderId) {
        ReturnOrderEntity returnOrder = returnOrderService.getById(returnOrderId);
        if (returnOrder.getStatus() == ReturnOrderStatus.SHIPPED.getValue()) {
            return Result.error("退货单已装车");
        }
        if (returnOrder.getStatus() == ReturnOrderStatus.CHECKED.getValue()) {
            return Result.error("退货单已经核验签收");
        }
        returnOrder.setStatus(ReturnOrderStatus.CANCEL.getValue());
        returnOrderService.updateReturnOrder(returnOrder);
        // 更新退货次数
        OrderEntity order = orderService.getById(returnOrder.getOrderId());
        order.setReturnNumber(0);
        orderService.updateOrder(order);
        // 创建即时消息
        noticeService.createReturnOrderNotice(returnOrder, ReturnOrderStatus.CANCEL);
        // 移除所有超时提醒
        redisDelayQueueManager.removeTask(ReturnTimeoutCheckTask.TAG + returnOrder.getId());
        return Result.success();
    }

    @SysLog(title = "删除退货单", businessType = BusinessType.DELETE)
    @ApiOperation("删除退货单")
    @RequiresPermissions()
    @DeleteMapping("/delete/{returnOrderId}")
    public Result delete(@PathVariable("returnOrderId") long returnOrderId) {
        returnOrderService.deleteReturnOrder(returnOrderId);
        // 移除所有超时提醒
        redisDelayQueueManager.removeTask(ReturnTimeoutCheckTask.TAG + returnOrderId);
        return Result.success();
    }
}
